<template>
  <view class="clock-header">
    <!-- 选择天数/关数 -->
    <view v-if="showMoreHandle" class="clock-header__selector">
      <picker
        mode="selector"
        :range="topData"
        :range-key="'title'"
        :value="topSelectIndex"
        @change="handleChange"
      >
        <text>{{ topData[~~topSelectIndex].title }}</text>
        <image :lazy-load="true" :src="SELECTOR_ARROWS" />
      </picker>
    </view>
    <view v-else class="clock-header__selector">
      <text>{{ clockDetail.checkpoint_text }}</text>
    </view>

    <!-- 模块选择区域 -->
    <view v-if="showMoreHandle" class="clock-header__modules">
      <view
        @tap="handlerModules(handler)"
        v-for="({ image, title, handler }, index) in moduleslist"
        :key="index"
        class="clock-header__modules__item"
      >
        <image :lazy-load="true" :src="image" />
        <text>{{ title }}</text>
      </view>
    </view>

    <!-- 主题内容 -->
    <view class="clock-header__theme-content" :class="themeContentClass">
      <view class="clock-header__theme-content__title" :style="themeTitleStyle">主题</view>

      <view class="clock-header__theme-content__content">
        <view
          class="clock-header__theme-content__content--item"
          v-for="(item, index) in clockDetail.content"
          :key="index"
        >
          <view
            class="clock-header__theme-content--item__text"
            v-if="item.type === 'text'"
          >{{ item.content }}</view>
          <image @tap="openImage(item.content)" v-if="item.type === 'image'" :src="item.content" />
          <video
            @pause="onVideoPause(item)"
            @play="onVideoPlay(item)"
            :id="item.uuid"
            v-if="item.type === 'video'"
            :src="item.content"
          />
        </view>
      </view>

      <view
        v-if="showFold && themeContentMax"
        @tap="foldContent"
        class="clock-header__theme-content__fold"
        :class="foldBtnClass"
      >
        <text>{{ foldBtnText }}主题</text>
        <image :lazy-load="true" :src="FOLD_ARROWS" />
      </view>

      <!-- 收起内容时底部遮罩 -->
      <view
        @tap="foldContent"
        v-show="foldStatus && showFold && themeContentMax"
        class="fold-shade"
      ></view>
    </view>

    <!-- 打卡日签 -->
    <ClockSign
      @clockShare="clockShare"
      @onClose="onClose"
      :student-id="clockDetail.student_id"
      :theme-id="clockDetail.id"
      :uuid="clockDetail.uuid"
      :show.sync="showShare"
    />
    <!-- 邀请好友 -->
    <Invite @onClose="onClose" :invite-data="inviteData" :show.sync="showInvite" />
  </view>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import Taro from "@tarojs/taro";
import CustomHeader from "@/components/custom-header/index.vue";
import ClockSign from "@/components/generate-image/index.vue";
import Invite from "@/components/generate-image/invite.vue";
import {
  SELECTOR_ARROWS,
  MODULE_BGI,
  INVITE,
  RANKING,
  CLOCK_SIGN,
  THEME_TITLE_BGI,
  FOLD_ARROWS,
} from "@/config/component-config/clock-header";

const OFFSET = 10; // 距离顶部便宜量
const GASBAG_TITLE_OFFSET = 20; // 顶部气囊按钮向下偏移量 总共标题的高 = 气囊的高度 + 距离顶部的位置 + 此偏移量
/* 模块列表接口 */
interface ModuleList {
  image: string;
  title: string;
  handler: string;
}

@Component({
  components: { CustomHeader, ClockSign, Invite },
})
export default class ClockHeader extends Vue {
  SELECTOR_ARROWS: string = SELECTOR_ARROWS;
  FOLD_ARROWS: string = FOLD_ARROWS;

  /* 天数选择显示 */
  showSelector: boolean = false;
  /* 当前选择 */
  cuurentSelector = { id: 0, title: "" };
  /* 折叠状态 */
  foldStatus: boolean = false;
  /* 模块列表 */
  moduleslist: ModuleList[] = [
    { title: "邀请好友", image: INVITE, handler: "handlerInvite" },
    { title: "排行榜", image: RANKING, handler: "handlerRanking" },
    { title: "打卡日签", image: CLOCK_SIGN, handler: "handlerClockSign" },
  ];
  /* 顶部数据列表 */
  topData = [];
  topSelectIndex: String = "0";
  /* 打卡日签显示 */
  showShare: boolean = false;
  /* 邀请好友显示 */
  showInvite: boolean = false;
  /* 主题内容文字超出 */
  themeContentMax: boolean = false;
  canShowClockSign: boolean = false;
  videoArr = [];

  /* props */
  /* 是否显示展开按钮 */
  @Prop({ default: false }) readonly showFold?: boolean;

  /* 是否展示切换按钮 和操作区域 */
  @Prop({ default: true }) readonly showMoreHandle?: boolean;

  @Prop({ default: 0 }) readonly themeId?: number;

  /* 选项 */
  @Prop({ default: () => [] }) readonly topDataIn?;

  /* 传进来的内容 富文本 和id 其他的展示不知道有什么 */
  @Prop({
    default: () => {
      return {};
    },
  })
  readonly clockDetail;
  @Watch("mediaPlayFlag")
  changemediaFlag(n) {
    n && n !== -1 && this.closeOtherVideo(n);
  }
  @Watch("clockDetail", { deep: true })
  onChangeClockDetail() {
    this.canShowClockSign = true;
    /* 初始化视频实例 */
    this.initVideoContext();

    /* 判断是否显示折叠按钮 */
    this.showFold &&
      Taro.nextTick(() => {
        let query = Taro.createSelectorQuery();
        query
          .select(".clock-header__theme-content__content")
          .boundingClientRect((rect) => {
            let clientHeight = rect.height;
            let clientWidth = rect.width;
            let ratio = 750 / clientWidth;
            let height = clientHeight * ratio;
            this.themeContentMax = Math.ceil(height) > 650;
          })
          .exec();
      });
  }

  @Watch("topDataIn")
  changeShow(n, o) {
    this.topData = n;
    this.themeId &&
      this.topData.find((n, i) => {
        return this.themeId === n.id && (this.topSelectIndex = i + "");
      });
    console.log(n, this.topSelectIndex, "ssss");
  }
  created() {
    this.showFold && (this.foldStatus = true);
    this.getTopData();
  }

  /* computed */
  get mediaPlayFlag() {
    return this.$store.getters.mediaVideoFlag;
  }
  /* 是否有邀请还有数据 */
  get hasInviteData() {
    return Object.keys(this.inviteData).length;
  }

  /* 邀请好友数据 */
  get inviteData() {
    return this.clockDetail.invite_card || {};
  }

  /* 折叠按钮显示文字 */
  get foldBtnText() {
    return this.foldStatus ? "展开" : "折叠";
  }

  /* 主题内容 标题样式 */
  get themeTitleStyle() {
    return {
      background: `url(${THEME_TITLE_BGI})`,
      "background-size": "100% 100%",
    };
  }

  /* 主题详情图片 */
  get themeImage() {
    return this.clockDetail.content
      .filter((item) => {
        return item.type === "image";
      })
      .reduce((acc, item) => {
        return [...acc, item.content];
      }, []);
  }

  /* 主题内容样式 */
  get themeContentClass() {
    return this.themeContentMax && this.foldStatus ? "fixation-height" : "";
  }
  /* 展开收起按钮样式 */
  get foldBtnClass() {
    return this.foldStatus ? "closed-fold" : "open-fold";
  }

  /* 展开收起按钮样式 */
  get foldBtnClass() {
    return this.foldStatus ? "closed-fold" : "open-fold";
  }

  /* methods */
  /* 关闭其他视频 */
  closeOtherVideo(uuid) {
    this.videoArr.forEach((item) => {
      console.log(item);
      item.uuid !== uuid && item.context.pause();
    });
  }
  /* 视频暂停事件 */
  onVideoPause({ uuid }) {}
  /* 视频播放事件 */
  onVideoPlay({ uuid }) {
    this.$store.commit("setMediaVideoFlag", uuid);
  }
  /* 初始化视频实例 */
  initVideoContext() {
    this.videoArr = [];
    this.clockDetail.content.forEach((item) => {
      item.type === "video" &&
        this.videoArr.push({
          uuid: item.uuid,
          url: item.content,
          context: Taro.createVideoContext(item.uuid),
        });
    });
  }

  openImage(current) {
    Taro.previewImage({
      urls: this.themeImage,
      current,
    });
  }
  /* 日签长按分享事件 */
  clockShare(data) {
    this.$emit("clockShare", data);
    console.log(data, "datadata");
  }
  /* 日签关闭事件抛出 */
  onClose() {
    this.$emit("onClose", false);
  }
  /* 获取顶部数据 */
  async getTopData() {
    // const { data } = await topData();
    this.topDataIn.length && (this.topData = this.topDataIn);
    this.topDataIn &&
      this.topDataIn.length &&
      (this.cuurentSelector = this.topDataIn[0]);
  }
  /* 展开收起内容 */
  foldContent() {
    this.foldStatus = !this.foldStatus;
  }
  /* 点击相应模块 */
  handlerModules(eventName) {
    this[eventName]();
  }
  /* 点击邀请好友 */
  handlerInvite() {
    if (!this.hasInviteData)
      return Taro.showToast({ title: "数据加载中", icon: "none" });
    this.showInvite = true;
    console.log("handlerInvite");
    this.$emit("handlerInvite", this.clockDetail);
  }
  /* 点击排行榜 */
  handlerRanking() {
    if (this.clockDetail.countdown)
      return Taro.showToast({ title: "活动未开始", icon: "none" });
    Taro.navigateTo({
      url: `/pages/activity-ranking/index?id=${this.clockDetail.activity_id}`,
    });
  }
  /* 点击打卡日签 */
  handlerClockSign() {
    console.log(this.clockDetail, this.canShowClockSign, "1233333333333333");
    if (!this.hasInviteData)
      return Taro.showToast({
        title: "数据加载中",
        icon: "none",
      });
    this.showShare = true;
    this.$emit("handlerClockSign", this.clockDetail);
  }
  handleChange(e) {
    this.topSelectIndex = e.detail.value;
    this.$emit("pickChange", this.topData[~~this.topSelectIndex].id);
  }
}
</script>

<style lang="scss">
@import "@/assets/scss/tools.scss";
@import "@/assets/scss/theme.scss";
$moduleBg: "https://cdn-habitv5.xaxthk.cn/font-static/clock-header(1).png";
.clock-header {
  &__selector {
    @include normal-flex;
    margin-top: 22px;
    font-size: 32px;
    font-weight: bold;
    color: $text-color-primary;
    position: relative;
    // line-height: 32px;
    image {
      width: 19px;
      height: 11px;
      margin-left: 16px;
      vertical-align: middle;
      margin-bottom: 10px;
    }
  }
  &__scroll-view {
    position: absolute;
    width: 288px;
    max-height: 360px;
    left: 50%;
    top: 64px;
    z-index: 2;
    transform: translateX(-50%);
    background-color: #fff;
    border-radius: 20px;
    &::after {
      content: "";
      border: 10px solid transparent;
      border-bottom: 10px solid #fff;
      position: absolute;
      top: -20px;
      left: 50%;
      transform: translateX(-50%);
    }
    &__item {
      @include normal-flex;
      height: 88px;
      line-height: 88px;
      font-size: 28px;
      border-bottom: 2px solid #f3f3f3;
    }
  }
  &__modules {
    margin-top: 38px;
    padding: 0 30px;
    @include normal-flex(space-between);
    &__item {
      width: 214px;
      height: 174px;
      background: url($moduleBg) no-repeat;
      background-size: 100% 100%;
      font-size: 24px;
      @include normal-flex;
      flex-direction: column;
      > image {
        width: 72px;
        height: 72px;
        margin-bottom: 4px;
      }
    }
  }
  &__theme-content {
    margin-top: 46px;
    text-align: center;
    padding: 0 30px;
    &__title {
      display: inline-block;
      width: 394px;
      height: 80px;
      line-height: 80px;
      margin-bottom: 30px;
      color: #a13d0f;
      letter-spacing: 6px;
      font-size: 36px;
    }
    &__content {
      font-size: 28px;
      line-height: 48px;
      text-align: center;
      word-break: break-all;
      &--item {
        margin: 32px 0;
        > video {
          width: 100%;
          border-radius: 16px;
        }
        > image {
          min-width: 100%;
          vertical-align: middle;
          border-radius: 16px;
        }
      }
      &--text {
        text-align: left;
      }
    }
    &__fold {
      width: 260px;
      height: 64px;
      background: #ffffff;
      border-radius: 100px;
      color: #a13d0f;
      margin-top: 32px;
      font-size: 28px;
      margin: 32px 0 0 216px;
      @include normal-flex;
      > image {
        width: 32px;
        height: 32px;
        margin-left: 12px;
        transform: rotate(0);
      }
    }
    .closed-fold {
      position: absolute;
      bottom: 40px;
      left: 50%;
      transform: translateX(-50%);
      margin: 0;
      z-index: 1;
      > image {
        transform: rotate(180deg);
      }
    }
    .fold-shade {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 120px;
      background: linear-gradient(
        180deg,
        rgba(255, 247, 224, 0) 0%,
        #fff7e0 100%
      );
      z-index: 2;
    }
  }
  .fixation-height {
    overflow: hidden;
    height: 650px;
    position: relative;
  }
}
</style>
